<template>
  <div>
    <el-card class="ivu-mt">
      <el-form :model="addForm" :rules="addRules" ref="AddRefForm" label-width="90px">
        <el-form-item label="插图" prop="img" ref="imageImgRef">
          <el-upload
            ref="imgRef"
            :action="upload.url"
            :headers="upload.headers"
            :accept="upload.accept"
            list-type="picture-card"
            :data="upload.data"
            :limit="upload.limitCount"
            :file-list="filePath"
            :on-remove="handleRemove"
            :on-exceed="onExceed"
            :on-success="onSuccess"
            :on-preview="handlePictureCardPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="公司资质" prop="uploadList" ref="imageQuaRef">
          <el-upload
            ref="quaRef"
            :action="upload.url"
            :headers="upload.headers"
            :accept="upload.accept"
            list-type="picture-card"
            :data="upload.data"
            :limit="25"
            :file-list="qualifications"
            multiple
            :on-remove="qualificationsHandleRemove"
            :on-success="qualificationSuccess"
            :on-preview="handlePictureCardPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-upload
          style="display: none"
          class="quill-avatar-uploader"
          :action="upload.url"
          :headers="upload.headers"
          :accept="upload.accept"
          :data="upload.data"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :before-upload="beforeUpload"></el-upload>
        <el-form-item label="内容">
          <el-row v-loading="quillUpdateImg">
            <quill-editor ref="myQuillEditor" v-model="addForm.content"  class="ql-editor-class" :options="editorOption"></quill-editor>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">立即更新</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
const toolbarOptions = [
  // toggled buttons
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote'],
  // custom button values
  [{'header': 1}, {'header': 2}],
  [{'list': 'ordered'}, {'list': 'bullet'}],
  // superscript/subscript
  [{'script': 'sub'}, {'script': 'super'}],
  // outdent/indent
  [{'indent': '-1'}, {'indent': '+1'}],
  // text direction
  [{'direction': 'rtl'}],
  [{'size': ['10px', '12px', '14px', '16px', '18px', '20px', '22px', '24px', '26px', '32px', '48px']}],
  // custom dropdown
  [{'header': [1, 2, 3, 4, 5, 6, false]}],
  // dropdown with defaults from theme
  [{'color': []}, {'background': []}],
  [{'font': []}],
  [{'align': []}],
  ['image'],
  // remove formatting button
  ['clean']
]
export default {
  name: "index",
  data(){
    let checkImg = (rule, value, callback) => {
      if (!this.hasFmt) { //hasFmt设置为true/false
        callback(new Error("请上传插图图片"));
      } else {
        callback();
      }
    }
    let checkQuaImg = (rule, value, callback) => {
      if (!this.hasQuaFmt) { //hasFmt设置为true/false
        callback(new Error("请上传资质图片"));
      } else {
        callback();
      }
    }
    return{
      addForm:{
        img:[],
        content:'',
        uploadList:[],
      },
      qualifications:[],
      filePath:[],
      quillUpdateImg:false,
      hasFmt:false,
      hasQuaFmt:false,
      dialogImageUrl: '',
      dialogVisible: false,
      addRules:{
        img: [{ required: true, validator: checkImg }],
        uploadList: [{ required: true, validator: checkQuaImg }]
      },
      upload: {
        url: this.$action_url,
        headers: {Authorization: window.sessionStorage.getItem('token')},
        data:{
          folder:'about_img'
        },
        name: 'file',
        accept: 'image/*',
        limitCount: 1,
      },
      //编辑器配置
      editorOption:{
        placeholder: '请输入内容',
        theme: 'snow',
        modules: {
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          },
          toolbar: {
            container:toolbarOptions,
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector(".quill-avatar-uploader input").click();
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      }
    }
  },
  created() {
    this.getIntroduceList()

  },
  methods:{
    async getIntroduceList(){
      const {data: res} = await this.$http.get('dashboard/introduce_list')
      if (res.code !== 200) return this.$message.error(res.data.message)
      this.addForm = res.data.content
      this.filePath = res.data.content.img
      this.hasFmt = true;
      this.hasQuaFmt = true;
      this.qualifications = res.data.content.qualifications
    },
    goBack(){
      this.$router.go(-1);//返回上一层
    },
    handleRemove(file){
      const i = this.addForm.img.findIndex(x => x.image === file)
      //通过数组的splice方法 把图片从img_path 数组中删除
      this.addForm.img.splice(i, 1)
      if(this.addForm.img.length === 0){
        this.hasFmt = false;
      }
      this.$refs.imageImgRef.validate();
    },
    onExceed(files, fileList){
      if(files.length === 1){
        return this.$message.error('图片超出1张图片的限制,请删除后重新上传')
      }
    },
    // 上传图片前
    beforeUpload(res, file) {
      // 打开上传动画
      this.quillUpdateImg = true
    },
    // 上传图片成功
    uploadSuccess(res,file,fileList) {
      let quill = this.$refs.myQuillEditor.quill
      if (res.code !== 200) return this.$message.error('上传失败');
      // 获取光标所在位置
      let length = quill.getSelection().index;
      // 插入图片  res.info为服务器返回的图片地址
      quill.insertEmbed(length, 'image', this.$http_url + 'storage/' + res.data.list.path)
      // 调整光标到最后
      quill.setSelection(length + 1)

      // loading动画消失
      this.quillUpdateImg = false
    },
    // 上传图片失败
    uploadError(res, file) {
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    onSuccess(response, file, fileList){
      if (response.code !== 200) return this.$message.error(response.data.message)
      this.hasFmt = true;
      const path = {url:this.$http_url + 'storage/' + response.data.list.path,uid:file.uid,name:file.name}
      this.addForm.img.push(path)
      this.$refs.imageImgRef.clearValidate();
    },
    //资质移除
    qualificationsHandleRemove(file){
      const i = this.addForm.uploadList.findIndex(x => x.uid === file.uid)
      //通过数组的splice方法 把图片从img_path 数组中删除
      this.addForm.uploadList.splice(i, 1)
      if(this.addForm.uploadList.length === 0){
        this.hasQuaFmt = false;
      }
      this.$refs.imageQuaRef.validate();
    },
    //资质图片上传
    qualificationSuccess(response, file, fileList){
      if (response.code !== 200) return this.$message.error(response.data.message)
      this.hasQuaFmt = true;
      const path = {url:this.$http_url + 'storage/' + response.data.list.path,uid:file.uid,name:file.name}
      this.addForm.uploadList.push(path)
      this.$refs.imageQuaRef.clearValidate();
    },
    save(){
      this.$refs.AddRefForm.validate(async valid => {
        if (!valid) return this.$message.error('输入不合法')
        console.log(this.addForm)
        const {data: result} = await this.$http.post('dashboard/save_introduce', this.addForm)
        if (result.code !== 200) return this.$message.error(result.data.message)
        this.$message.success('更新成功')
        this.getIntroduceList()
      })
    }
  }
}
</script>

<style scoped>

</style>
